package com.example.securitymy.filter;


import com.example.securitymy.domain.LoginUser;
import com.example.securitymy.utils.JwtUtil;
import com.example.securitymy.utils.RedisCache;
import io.jsonwebtoken.Claims;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Resource
    RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        System.out.println("=================================这里是Jwt过滤器=================================");
        System.out.println("token:"+token);
        if(StringUtils.isEmpty(token)){
            filterChain.doFilter(request,response);
            return;
        }
        String subject;
        // 登录接口中只把userID当作了subject,下面解析userID
        try {
            Claims claims = JwtUtil.parseJWT(token);
            subject =claims.getSubject();
        }catch (Exception e){
            //解析失败
            throw new RuntimeException("token非法");
        }
        System.out.println(subject);
        //拼接redisKey并从redis中获取loginUser
        String redisKey = "login:"+subject;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(loginUser == null){
            throw new RuntimeException("用户未登录");
        }
        //将认证信息存入SecurityContextHolder（用户信息，，权限信息）
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request,response);
    }
}
